//merge census to PIKs using big crosswalk file

/*
use uid pik verflg using "$data/PIK/Census/stata/cen_pik_xwalk_cuf", clear
compress
drop if pik == ""
save "$data/PIK/Census/stata/cen_pik_xwalk_cuf_small", replace //optimized version
*/

//step 1: reshape data to just have kids with parent covariates
local states `"ak al ar az ca co ct de fl ga hi ia id il in ks ky la ma md me mi mn mo ms mt nc nd ne nh nj nm nv ny oh ok or pa ri sc sd tn tx ut va vt wa wi wv wy"'

qui{
foreach state in `states'{
	noi di as result "Working on state `i': `state'"
	use "$temp/census_long_`state'", clear
	local vars `"qspan qdb qage qincwg qwklyrwk qwklyrhr qinctot pern pov qsex imprace qms qhigh qspeak qcitizen qpobst esr qocc qcow disable qind"'

	//get head covariates
	preserve
	keep if qrel == "01"
	keep mafid `vars'

	foreach var in `vars'{
		ren `var' `var'_head
	}

	tempfile head
	save `head'
	restore

	//spouse covariates
	preserve
	keep if qrel == "02"
	keep mafid `vars'

	foreach var in `vars'{
		ren `var' `var'_sp
	}

	tempfile spouse
	save `spouse'
	restore

	//limit to kids and merge
	keep if birth_yr>=1983 & birth_yr<=1994 //kids	
	local vars_personal `"mafid pwt pseq pnc qrel birth_yr"'
	local vars_house `"srent hinc finc rrt smortgd smhcost sconfee stenure sbldgsz svalue smortg hwt"'
	local vars_geo `"bcseq state county tract block blkgrp ur"'
	keep `vars_personal' `vars_house' `vars_geo' //variable restriction
	
	//get parent covariates
	merge m:1 mafid using `head', keep(match) nogen
	merge m:1 mafid using `spouse', keep(1 3) nogen
	

	//variable renaming
	foreach var in `vars_house'{
		ren `var' `var'_2000
	}

	foreach var in `vars_geo'{
		ren `var' `var'_2000
	}
	
	//construct uid for merging
	gen uid = "C" + mafid + pseq + pnc //unique identifier
	compress
	save "$temp/census_long_`state'_pik", replace	
}
}

local states `"ak al ar az ca co ct de fl ga hi ia id il in ks ky la ma md me mi mn mo ms mt nc nd ne nh nj nm nv ny oh ok or pa ri sc sd tn tx ut va vt wa wi wv wy"'
clear

foreach state in `states'{
	append using "$temp/census_long_`state'_pik"
}

//big merge!
merge 1:1 uid using "$data/PIK/Census/stata/cen_pik_xwalk_cuf_small", keep(1 3) nogen //keep non-matches 
save "$temp/census_long_pik_master", replace

//end of do-file

